package pl.edu.pw.elka.tinyrepo.gate.server;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.util.StringTokenizer;

import pl.edu.pw.elka.tinyrepo.common.CatalogContent;
import pl.edu.pw.elka.tinyrepo.common.CatalogContentSerializer;
import pl.edu.pw.elka.tinyrepo.common.FileProperties;
import pl.edu.pw.elka.tinyrepo.common.FilePropertiesSerializer;
import pl.edu.pw.elka.tinyrepo.common.HTTPHeaderType;
import pl.edu.pw.elka.tinyrepo.common.Request;
import pl.edu.pw.elka.tinyrepo.common.RequestHandler;
import pl.edu.pw.elka.tinyrepo.common.Response;
import pl.edu.pw.elka.tinyrepo.common.StatusCode;
import pl.edu.pw.elka.tinyrepo.common.exceptions.WrongPathException;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.CatalogDescriptor;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.Descriptor;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.FileDescriptor;
import pl.edu.pw.elka.tinyrepo.gate.descriptor.RepoDescriptor;
import sun.security.provider.certpath.OCSPResponse.ResponseStatus;


/**
 * @author: Kajot
 */

class PROPFINDRequestHandler extends GateRequestHandler {
   
   public PROPFINDRequestHandler(RepoDescriptor desc) {
      super(desc);
   }
   
   @Override
   public void run() {
      OutputStream out = null;
      try {
    	  
         out = incomming.getOutputStream(); // wyjscie do klienta
         String requestPath = request.getPath(); // wyciagniecie sciezki do pliku 

         Descriptor d = desc.getFileOrDirectoryDesc(requestPath);

         // PLIK
         if(d.getClass() == FileDescriptor.class) {
        	 
        	 FileDescriptor fd = (FileDescriptor) d;
        	 
        	 Response res = new Response(StatusCode.MOVED_PERMANENTLY);
        	 res.addHeader(HTTPHeaderType.LOCATION, fd.getDestination()+"/"+fd.getId());
        	 res.write(out);
        	 System.out.println("Sent response: "+res);
        	 System.out.println("PROPFIND redirected to " + fd.getDestination()+"/"+fd.getId());
        	 
         }

         // KATALOG
         if(d.getClass() == CatalogDescriptor.class) {
            
            CatalogDescriptor cd = ((CatalogDescriptor)d);
            StringTokenizer tkzr = new StringTokenizer(requestPath,"/");
            String name = "/";
            while(tkzr.hasMoreTokens()) {
               name = tkzr.nextToken();
            }
            FileProperties fp = new FileProperties(name, cd.getSize(), 0);
            FilePropertiesSerializer serializer = new FilePropertiesSerializer();
            String xml = serializer.toXML(fp);
            Response res = new Response(StatusCode.OK);
            res.addHeader(HTTPHeaderType.CONTENT_LENGTH, Integer.toString(xml.length()));
            res.addHeader(HTTPHeaderType.CONTENT_TYPE, "application/xml; charset=\"utf-8\"");
            res.write(out);
            // zapisywanie xmla
            System.out.println("Sent response: \n"+res);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(xml);
            writer.flush();
         }
         
         
      }catch (FileNotFoundException e) { // pliku nie ma
         e.printStackTrace();
         Response rs = new Response(StatusCode.NOT_FOUND);
         rs.write(out);
      }
      catch (WrongPathException e) { // nieprawidlowa sciezka do pliku
         e.printStackTrace();
         Response rs = new Response(StatusCode.NOT_FOUND);
         rs.write(out);
      }
      catch (IOException e) {
         // cos nie tak z polaczeniem, nic nie wysylaj, wyswietl info na serwerze
         e.printStackTrace();
      }
      // socket jest zamykany w klasach DAVServer
   }


   @Override
   public RequestHandler copy() {
      return new PROPFINDRequestHandler(desc);
   }
}
